<?php
/**
 * Description of generator
 *
 * @author Андрей
 */
class Generator
{
    public static function factory($driver)
    {
        $class = 'Generator_'.$driver;
        return new $class();
    }

    public function parse_fields($model_sheme, $separator = "\n")
    {
        $fields = array();
        $lines = explode($separator, $model_sheme);
        foreach ($lines as $line)
        {
            $fields[] = $this->parse_field($line);
        }
        return $fields;
    }

    /**
     * Create module directory structur by module name
     * @param string $name module name
     * @return array all created path
     */
    public function create_module($name)
    {
        $dir = Kohana::config('app.folder');
        $set_dir = ($dir != '');

        $module_path = MODPATH . $name . DIRECTORY_SEPARATOR;
        $this->mkdir($module_path);

        $classes_path = $module_path . 'classes' . DIRECTORY_SEPARATOR;
        $this->mkdir($classes_path);

        $generator_path = $classes_path . 'generator' . DIRECTORY_SEPARATOR;
        $this->mkdir($generator_path);

        $controller_path = $classes_path . 'controller' . DIRECTORY_SEPARATOR;
        $this->mkdir($controller_path);

        if ($set_dir)
        {
            $controller_path .= $dir.DIRECTORY_SEPARATOR;
            $this->mkdir($controller_path);
        }

        $model_path = $classes_path . 'model' . DIRECTORY_SEPARATOR;
        $this->mkdir($model_path);

        $views_path = $module_path . 'views' . DIRECTORY_SEPARATOR;
        $this->mkdir($views_path);
        
        if ($set_dir)
        {
            $views_path .= $dir.DIRECTORY_SEPARATOR;
            $this->mkdir($views_path);
        }

        return array(
            'module' => $module_path,
            'classes' => $classes_path,
            'generator' => $generator_path,
            'controller' => $controller_path,
            'model' => $model_path,
            'views' => $views_path,
        );
    }

    public function mkdir($dir)
    {
        if (!is_dir($dir))
            mkdir($dir, true);
    }

    public function save_file($dest, $text)
    {
        if ( ! is_dir(dirname($dest)))
            mkdir(dirname($dest), 644, TRUE);

        file_put_contents ($dest, $text);
    }
}
?>
